"""风险分析汇总."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, Iterable

import pandas as pd

from .risk_metrics import (
    DrawdownMetrics,
    LiquidityMetrics,
    VolatilityMetrics,
    calculate_liquidity_metrics,
    calculate_max_drawdown,
    calculate_rolling_volatility,
    calculate_var,
)


@dataclass(frozen=True)
class RiskSummary:
    volatility: VolatilityMetrics
    drawdown: DrawdownMetrics
    liquidity: LiquidityMetrics
    value_at_risk: float


def build_risk_summary(
    frame: pd.DataFrame,
    *,
    price_column: str = "close",
    volume_column: str = "volume",
    shares_outstanding: int | None = None,
    volatility_windows: Iterable[int] = (20, 60),
    var_confidence: float = 0.95,
) -> RiskSummary:
    """根据 OHLCV 数据计算风险汇总."""

    if price_column not in frame.columns:
        raise ValueError(f"缺少价格列 {price_column}")
    if volume_column not in frame.columns:
        raise ValueError(f"缺少成交量列 {volume_column}")

    prices = frame[price_column]
    volume = frame[volume_column]
    returns = prices.pct_change().dropna()

    volatility = calculate_rolling_volatility(returns, windows=volatility_windows)
    drawdown = calculate_max_drawdown(prices)
    liquidity = calculate_liquidity_metrics(volume, shares_outstanding=shares_outstanding)
    var_value = calculate_var(returns, confidence=var_confidence)

    return RiskSummary(
        volatility=volatility,
        drawdown=drawdown,
        liquidity=liquidity,
        value_at_risk=var_value,
    )

